<template>
  <el-dialog
    v-model="showDialog"
    :title="popTitle"
    width="600px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      class="page-form"
    >
      <el-form-item :label="t('logo')" prop="logo">
        <div class="flex justify-center items-center">
          <upload-image v-model="formData.logo" />
        </div>
      </el-form-item>
      <el-form-item :label="t('name')" prop="name">
        <div class="flex justify-center items-center">
          <el-input
            v-model.trim="formData.name"
            :placeholder="t('namePlaceholder')"
            maxlength="50"
            show-word-limit
            clearable
            class="input-width mr-[15px]"
          />
          <el-switch
            v-model="showObj.name"
            active-text="显示"
            inactive-text="隐藏"
            :active-value="1"
            :inactive-value="0"
          />
        </div>
      </el-form-item>
      <el-form-item :label="t('year')" prop="year">
        <div class="flex justify-center items-center">
          <el-input
            v-model.trim="formData.year"
            :placeholder="t('yearPlaceholder')"
            show-word-limit
            type="number"
            clearable
            class="input-width mr-[15px]"
          />
          <el-switch
            v-model="showObj.year"
            active-text="显示"
            inactive-text="隐藏"
            :active-value="1"
            :inactive-value="0"
          />
        </div>
      </el-form-item>
      <el-form-item :label="t('flavor')" prop="flavor">
        <div class="flex justify-center items-center">
          <el-input
            v-model.trim="formData.flavor"
            :placeholder="t('flavorPlaceholder')"
            maxlength="100"
            show-word-limit
            clearable
            class="input-width mr-[15px]"
          />
          <el-switch
            v-model="showObj.flavor"
            active-text="显示"
            inactive-text="隐藏"
            :active-value="1"
            :inactive-value="0"
          />
        </div>
      </el-form-item>
      <el-form-item :label="t('recommendRatio')" prop="recommendRatio">
        <div class="flex justify-center items-center">
          <el-slider
            v-model="recommendRatio"
            range
            :format-tooltip="(v: number) => v + '%'"
            class="input-width mr-[15px]"
            @change="changeRecommendRatio"
          />
          <el-switch
            v-model="showObj.recommendRatio"
            active-text="显示"
            inactive-text="隐藏"
            :active-value="1"
            :inactive-value="0"
          />
        </div>
      </el-form-item>
      <el-form-item :label="t('price')" prop="price">
        <div class="flex justify-center items-center">
          <el-input
            v-model.trim="formData.price"
            :placeholder="t('pricePlaceholder')"
            type="number"
            class="input-width mr-[15px]"
          >
            <template #suffix>
              <span>/500ml</span>
            </template>
          </el-input>
          <el-switch
            v-model="showObj.price"
            active-text="显示"
            inactive-text="隐藏"
            :active-value="1"
            :inactive-value="0"
          />
        </div>
      </el-form-item>
      <el-form-item :label="t('change_percentage')" prop="change_percentage">
        <div class="flex justify-center items-center">
          <div class="input-width mr-[15px]">
            <el-tag
              v-for="(tag, index) in formData.change_percentage"
              :key="index"
              closable
              :disable-transitions="false"
              @close="removeRatios(tag)"
              class="mr-[10px]"
            >
              {{ tag }}%
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              size="small"
              type="number"
              :min="0"
              :max="100"
              :placeholder="t('change_percentagePlaceholder')"
              @keyup.enter="saveRatios"
              @blur="saveRatios"
              class="width-short"
            />
            <el-button v-else class="width-short" size="small" @click="showInput">
              + 新增占比
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="t('sort')" prop="sort">
        <el-input-number
          v-model="formData.sort"
          ::step="1"
          step-strictly
          :value-on-clear="0"
          :min="0"
          class="input-width"
          :placeholder="t('sortPlaceholder')"
        />
      </el-form-item>
      <el-form-item v-if="formId != 0" :label="t('status')">
        <el-radio-group v-model="formData.status">
          <el-radio :value="1">{{ t("statusUnlock") }}</el-radio>
          <el-radio :value="0">{{ t("lock") }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">{{ t("cancel") }}</el-button>
        <el-button type="primary" :loading="loading" @click="confirm(formRef)">
          {{ t("confirm") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, toRaw, nextTick } from "vue";
import { t } from "@/lang";
import type { FormInstance, InputInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { addBodyApi, editBodyApi } from "@/app/api/alcohol";
import { deepClone } from "@/utils/common";

const showDialog = ref(false);
const loading = ref(false);
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref<InputInstance>();
let popTitle: string = "";
const recommendRatio = ref([0, 100]); // 比例
const showObj = ref<any>({
  name: 1, // 显示酒体名称
  year: 1, // 显示年份
  flavor: 1, // 显示风味特色
  recommendRatio: 1, // 显示比例
  price: 1, // 显示价格
});

/**
 * 表单数据
 */
const formId = ref<number>(0);
const initialFormData = {
  logo: "", // 酒体图片
  type_id: 0, // 酒体类型
  name: "", // 酒体名称
  year: "", // 年份
  flavor: "", // 风味特色
  price: "", // 价格
  min_percentage: 0, // 最小比例
  max_percentage: 100, // 最大比例
  change_percentage: [], // 占比参数
  sort: 0, // 排序
  status: null, // 状态
  show_json: "", // 显示字段
};
const formData: Record<string, any> = reactive({ ...initialFormData });

const formRef = ref<FormInstance>();

// 表单验证规则
const formRules = computed(() => {
  return {
    logo: [{ required: true, message: t("logoPlaceholder"), trigger: "blur" }],
    name: [{ required: true, message: t("namePlaceholder"), trigger: "blur" }],
    price: [{ required: true, message: t("pricePlaceholder"), trigger: "blur" }],
    change_percentage: [
      {
        required: true,
        type: "array",
        message: t("change_percentagePlaceholder"),
        trigger: ["blur", "change"],
      },
    ],
  };
});

const emit = defineEmits(["complete"]);

/**
 * 确认
 * @param formEl
 */
const confirm = async (formEl: FormInstance | undefined) => {
  if (loading.value || !formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      loading.value = true;
      const data = deepClone(toRaw(formData));
      data.show_json = JSON.stringify(showObj.value);
      data.change_percentage = data.change_percentage.sort(
        (a, b) => Number(a) - Number(b)
      );
      data.change_percentage = data.change_percentage.join(",");
      if (formId.value) {
        editBodyApi(formId.value, data)
          .then(() => {
            showDialog.value = false;
            emit("complete");
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        addBodyApi(data)
          .then(() => {
            showDialog.value = false;
            emit("complete");
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
};

// 删除占比参数
const removeRatios = (tag: string) => {
  formData?.change_percentage?.splice(formData?.change_percentage?.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

// 新增占比参数
const saveRatios = () => {
  if (inputValue.value && inputValue.value >= 0 && inputValue.value <= 100) {
    formData?.change_percentage?.push(inputValue.value);
  } else {
    ElMessage.error(t("change_percentageError"));
  }
  inputVisible.value = false;
  inputValue.value = "";
};

// 选择推荐比例
const changeRecommendRatio = (val: number[]) => {
  formData.min_percentage = val[0];
  formData.max_percentage = val[1];
};

const setFormData = (row: any = null) => {
  loading.value = true;
  Object.assign(formData, initialFormData);

  if (row?.id) {
    popTitle = t("updateWineBody");
    formId.value = row.id;
    Object.keys(formData).forEach((key: string) => {
      if (row[key] != undefined) formData[key] = row[key];
    });
    formData.change_percentage = row.change_percentage?.split(",");
    showObj.value = JSON.parse(row.show_json);
    recommendRatio.value = [row.min_percentage, row.max_percentage];
  } else {
    popTitle = t("addWineBody");
    formData.type_id = row?.type_id;
    Object.keys(showObj.value).forEach((key: string) => {
      showObj.value[key] = 1;
    });
    formData.change_percentage = [];
    recommendRatio.value = [0, 100];
    formId.value = 0;
  }
  loading.value = false;
};

defineExpose({
  showDialog,
  setFormData,
});
</script>

<style lang="scss" scoped>
.width-short {
  width: 100px;
}
</style>
